package io.noties.markwon.base.core.spans


import android.text.style.MetricAffectingSpan
import android.text.TextPaint
import android.text.style.LeadingMarginSpan
import android.graphics.Canvas
import android.graphics.Paint
import android.text.Layout
import com.gitee.wsl.ext.base.setAlpha
import io.noties.markwon.theme.MarkwonTheme

/**
 * @since 3.0.0 split inline and block spans
 */
class CodeBlockSpan(private val theme: MarkwonTheme) : MetricAffectingSpan(), LeadingMarginSpan {
    private val rect = ObjectsPool.rect()
    private val paint = ObjectsPool.paint()
    override fun updateMeasureState(p: TextPaint) {
        apply(p)
    }

    override fun updateDrawState(ds: TextPaint) {
        apply(ds)
    }

    private fun apply(p: TextPaint) {
        applyCodeBlockTextStyle(p)
    }

    private fun applyCodeBlockTextStyle(p: TextPaint) {}
    override fun getLeadingMargin(first: Boolean): Int {
        return theme.typography.codeBlockMargin
    }

    override fun drawLeadingMargin(
        c: Canvas,
        p: Paint,
        x: Int,
        dir: Int,
        top: Int,
        baseline: Int,
        bottom: Int,
        text: CharSequence,
        start: Int,
        end: Int,
        first: Boolean,
        layout: Layout
    ) {
        paint.style = Paint.Style.FILL
        //paint.setColor(theme.getColorTheme().getCodeBlockBackgroundColor(p));
        var color = (if (theme.colorTheme.codeBackgroundColor != 0L) theme.colorTheme.codeBlockBackgroundColor else theme.colorTheme.codeBackgroundColor).toInt()
        color = if (color != 0) color else paint.color.setAlpha( CODE_DEF_BACKGROUND_COLOR_ALPHA)
        paint.color = color
        val left: Int
        val right: Int
        if (dir > 0) {
            left = x
            right = c.width
        } else {
            left = x - c.width
            right = x
        }
        rect[left, top, right] = bottom
        c.drawRect(rect, paint)
    }

    companion object {
        protected const val CODE_DEF_BACKGROUND_COLOR_ALPHA = 25
    }
}